<template>
  <div class="supplier">
    <el-form class="boss-form" inline ref="form">
      <el-form-item label="供应商名称">
        <el-input class="boss_input" v-model="supplierData.search.supplierName" placeholder="请输入供应商名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="账号">
        <el-input class="boss_input" v-model="supplierData.search.supplierAccount" placeholder="请输入账号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <Button label="重置" @click="onResetClick" />
        <Button label="搜索" type="primary" @click="onSearchClick" />
      </el-form-item>
    </el-form>

    <div class="outerTable">
      <el-tabs v-if="route.meta.ori === 'cate' || route.meta.ori === 'account'" v-model="supplierData.search.status" type="card" @tab-click="onTabClick">
        <el-tab-pane label="待审核" name="AUDITING"></el-tab-pane>
        <el-tab-pane label="已通过" name="PASS"></el-tab-pane>
        <el-tab-pane label="已驳回" name="REJECTED"></el-tab-pane>
      </el-tabs>

      <el-table ref="tableRef" :height="tableHeight" :data="supplierData.list" v-loading="loading" @filter-change="onFilterChange">
        <el-table-column fixed="left" type="index" label="#" width="50" />
        <el-table-column label="供应商名称" prop="supplierName" />
        <el-table-column label="账号" prop="account" />
        <el-table-column
          v-if="route.meta.ori !== 'account' && route.meta.ori !== 'cate'"
          label="类目"
          prop="goodsType"
          :formatter="(row, column, cellValue, index) => $formater.formaterGoodsType(cellValue)"
          column-key="goodsType"
          :filter-multiple="false"
          :filters="
            Object.keys(consts.GoodsType).map((key) => {
              return { text: consts.GoodsType[key], value: key }
            })
          "
        />
        <el-table-column label="申请时间" prop="modifyTime" />
        <el-table-column v-if="route.meta.ori !== 'account' && route.meta.ori !== 'cate'" label="账号状态" prop="status">
          <template #default="scope">
            <span>{{ consts.AccountStatus[scope.row.status] }}</span>
            <el-switch v-if="authority.accountStatus" v-model="scope.row.status" active-value="UNFREEZE" inactive-value="FREEZE" :before-change="() => onSwitchChange(scope.row)" :loading="scope.row.statusSaving" />
          </template>
        </el-table-column>
        <el-table-column v-if="route.meta.ori !== 'account' && route.meta.ori !== 'cate'" label="资质权限状态" prop="qualificationStatus">
          <template #default="scope">
            <span>{{ consts.QualificationStatus[scope.row.qualificationStatus] }}</span>
            <el-switch v-if="authority.qualicationStatus" v-model="scope.row.qualificationStatus" active-value="ENABLED" inactive-value="FREEZE" :before-change="() => onQualicaSwitchChange(scope.row)" :loading="scope.row.qualicaStatusSaving" />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="130">
          <template #default="scope" v-if="route.meta.ori === 'account' || route.meta.ori === 'cate'">
            <Link label="审核" v-if="supplierData.search.accountAuditStatus === 'AUDITING' || supplierData.search.qualificationAuditStatus === 'AUDITING'" @click="onAuditClick(scope.row)" :underline="false"/>
            <Link v-else label="审核记录" @click="onAuditClick(scope.row)" :underline="false"/>
          </template>

          <template #default="scope" v-else>
            <Link label="详情" @click="onDetailClick(scope.row)" :underline="false"/>
            <Link v-if="authority.resetPwd" label="重置密码" @click="onResetPwdClick(scope.row)" :underline="false"/>
          </template>
        </el-table-column>
      </el-table>
      <Pager :page="supplierData.search.page" :total="supplierData.total" :limit="supplierData.search.limit" :pageSizes="supplierData.search.pageSizes" @current-change="onCurrentChange" @size-change="onSizeChange" />
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import formater from '@/formater'
import consts from '@/consts'
import { menuStore } from '@/store/menu.js'
import { calcTableHeight } from '@/assets/js/utils.js'
import Pager from '@/components/pager/index.vue'
import Link from '@/components/button/link.vue'
import Button from '@/components/button/button.vue'

const { tableRef, tableHeight } = calcTableHeight()
const router = useRouter()
const route = useRoute()
const _menuStore = menuStore()

const supplierData = reactive({
  total: 0,
  list: [],
  search: {
    page: 1,
    limit: consts.Limit,
    pageSizes: consts.PageSize,
    supplierName: '',
    supplierAccount: '',
    status: 'AUDITING',
    accountAuditStatus: '',
    qualificationAuditStatus: '',
    goodsType: ''
  }
})
const loading = ref(false)

const authority = reactive({
  accountStatus: false,
  qualicationStatus: false,
  monthlyStatus: false,
  resetPwd: false
})

watch(
  () => route.meta.ori,
  (val) => {
    if (val) {
      loadData()
    }
  }
)

const updateSupplierQualicaStatus = (supplierId, status) => {
  return api.post(`/medinstrument/boss/supplier/updateSupplierQualificationStatus?supplierId=${supplierId}&qualificationStatus=${status}`)
}

const updateSupplierStatus = (supplierId, status) => {
  return api.post(`/medinstrument/boss/supplier/updateSupplierStatus?supplierId=${supplierId}&status=${status}`)
}

const resetPwd = async (row) => {
  let { err } = await api.post(`/medinstrument/boss/supplier/reSetSupplierPwd?supplierId=${row.supplierId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('当前供应商密码重置成功，登录密码：Abc321，请通知用户尽快登录修改新密码')
  }
}

const loadData = async () => {
  loading.value = true
  if (route.meta.ori === 'cate') {
    supplierData.search.qualificationAuditStatus = supplierData.search.status
    supplierData.search.accountAuditStatus = ''
  } else if (route.meta.ori === 'account') {
    supplierData.search.accountAuditStatus = supplierData.search.status
    supplierData.search.qualificationAuditStatus = ''
  } else if (route.meta.ori === 'list') {
    supplierData.search.accountAuditStatus = ''
    supplierData.search.qualificationAuditStatus = ''
  }

  const params = { ...supplierData.search }
  delete params.status

  let { data, err } = await api.get('/medinstrument/boss/supplier/list', params)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    supplierData.list = data.list
    supplierData.total = data.count
  }
}

const onSwitchChange = (row) => {
  row.statusSaving = true
  const status = row.status === 'UNFREEZE' ? 'FREEZE' : 'UNFREEZE'
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(`${status === 'FREEZE' ? '是否确定停用当前供应商账号?停用后将下架该供应商所有商品,且该账户无法正常登录' : '是否确认启用当前供应商账号'}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const { err } = await updateSupplierStatus(row.supplierId, status)
        row.statusSaving = false
        if (err) {
          ElMessage.error(err)
          return reject(false)
        } else {
          return resolve(true)
        }
      })
      .catch(() => {
        row.statusSaving = false
        reject(false)
      })
  })
}

const onQualicaSwitchChange = (row) => {
  row.qualicaStatusSaving = true
  const status = row.qualificationStatus === 'ENABLED' ? 'FREEZE' : 'ENABLED'
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(`${status === 'FREEZE' ? '是否确定停用当前供应商资质权限?' : '是否确认启用当前供应商资质权限'}`, '系统', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const { err } = await updateSupplierQualicaStatus(row.supplierId, status)
        row.qualicaStatusSaving = false
        if (err) {
          ElMessage.error(err)
          return reject(false)
        } else {
          return resolve(true)
        }
      })
      .catch(() => {
        row.qualicaStatusSaving = false
        reject(false)
      })
  })
}

const onSearchClick = () => {
  supplierData.search.page = 1
  loadData()
}

const onResetClick = () => {
  supplierData.search = {}
  loadData()
}
const onTabClick = (tab) => {
  supplierData.search.status = tab.props.name
  loadData()
}

const onAuditClick = (row) => {
  if (route.meta.ori === 'account') {
    let { href } = router.resolve({
      path: `/supplier/accountDetail/${row.supplierId}`
    })
    window.open(href, '_blank')
  } else {
    let { href } = router.resolve({
      path: `/supplier/cateDetail/${row.supplierId}`
    })
    window.open(href, '_blank')
  }
}

const onDetailClick = (row) => {
  let { href } = router.resolve({
    path: `/supplier/detail/${row.supplierId}`
  })
  window.open(href, '_blank')
}

const onResetPwdClick = (row) => {
  ElMessageBox.confirm('确定要重置密码吗，不可恢复？', '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      resetPwd(row)
    })
    .catch(() => {})
}

const onCurrentChange = (val) => {
  supplierData.search.page = val
  loadData()
}

const onSizeChange = (val) => {
  supplierData.search.limit = val
  loadData()
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

const onFilterChange = (filters) => {
  Object.keys(filters).forEach((e) => {
    supplierData.search[e] = filters[e]
  })
  loadData()
}

onMounted(() => {
  loadData()
  authority.accountStatus = !!_menuStore.hasAuthorize('/medinstrument/boss/supplier/updateSupplierStatus')
  authority.qualicationStatus = !!_menuStore.hasAuthorize('/medinstrument/boss/supplier/updateSupplierQualificationStatus')
  authority.monthlyStatus = !!_menuStore.hasAuthorize('/medinstrument/boss/supplier/updateSupplierMonthly')
  authority.resetPwd = !!_menuStore.hasAuthorize('/medinstrument/boss/supplier/reSetSupplierPwd')
})
</script>
